package com.example.memo2.ui.home

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.memo2.R
import com.example.memo2.databinding.FragmentHomeBinding
import com.example.memo2.ui.MemoViewModel
import com.example.memo2.ui.detail.MemoDetailActivity
import com.example.memo2.utils.MediaUtils
import com.google.android.material.snackbar.Snackbar

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: MemoViewModel by activityViewModels()
    private lateinit var memoAdapter: MemoAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupRecyclerView()
        setupFab()
        observeData()
    }
    
    private fun setupRecyclerView() {
        memoAdapter = MemoAdapter(
            onItemClick = { memo ->
                // 跳转到详情页面
                val intent = Intent(requireContext(), MemoDetailActivity::class.java)
                intent.putExtra(MemoDetailActivity.EXTRA_MEMO_ID, memo.id)
                startActivity(intent)
            },
            onItemLongClick = { memo ->
                // 长按删除功能
                showDeleteConfirmDialog(memo)
                true
            }
        )
        
        binding.recyclerView.apply {
            adapter = memoAdapter
            layoutManager = LinearLayoutManager(context)
        }
    }
    
    private fun setupFab() {
        binding.fabAdd.setOnClickListener {
            // 跳转到新建备忘录页面
            val intent = Intent(requireContext(), MemoDetailActivity::class.java)
            intent.putExtra(MemoDetailActivity.EXTRA_IS_NEW, true)
            startActivity(intent)
        }
    }
    
    private fun observeData() {
        viewModel.allMemos.observe(viewLifecycleOwner) { memos ->
            memoAdapter.submitList(memos)
            updateEmptyState(memos.isEmpty())
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        if (isEmpty) {
            binding.recyclerView.visibility = View.GONE
            binding.emptyStateLayout.visibility = View.VISIBLE
        } else {
            binding.recyclerView.visibility = View.VISIBLE
            binding.emptyStateLayout.visibility = View.GONE
        }
    }
    
    private fun showDeleteConfirmDialog(memo: com.example.memo2.data.model.Memo) {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle(getString(R.string.delete_confirm_title))
            .setMessage(getString(R.string.delete_confirm_message))
            .setPositiveButton(getString(R.string.action_confirm)) { _, _ ->
                deleteMemo(memo)
            }
            .setNegativeButton(getString(R.string.action_cancel), null)
            .show()
    }
    
    private fun deleteMemo(memo: com.example.memo2.data.model.Memo) {
        viewModel.deleteMemo(memo)
        
        // 删除相关的媒体文件
        MediaUtils.parseImagePaths(memo.imagePaths).forEach { imagePath ->
            MediaUtils.deleteFile(imagePath)
        }
        memo.audioPath?.let { audioPath ->
            MediaUtils.deleteFile(audioPath)
        }
        
        Snackbar.make(binding.root, getString(R.string.memo_deleted), Snackbar.LENGTH_SHORT).show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}